package com.bawei.image

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import java.io.ByteArrayOutputStream

/**
 * Bitmap图片处理工具，主要用来压缩图片
 */
object BitmapUtil {

    /**
     * 方式一：质量压缩
     */
    fun compressQuality(resources: Resources, resId: Int, quality: Int): Bitmap {
        var bm = BitmapFactory.decodeResource(resources, resId)
        var bos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        var bytes = bos.toByteArray()
        return BitmapFactory.decodeByteArray(bytes, quality, bytes.size)
    }

    /**
     * 二次采样压缩
     */
    fun compressSecondBitmap(resources: Resources, resId: Int, maxWidth: Int, maxHeight: Int): Bitmap{
        var sampleSize = 1
        //第一次采样： 获取图片宽高
        var bitmapOptions = BitmapFactory.Options()
        bitmapOptions.inJustDecodeBounds = true //开启后，只加载图片的宽高大小，而不会加载实际像素值，所以不会消耗内存
        BitmapFactory.decodeResource(resources, resId, bitmapOptions)

        //获取原始图片宽高
        var bmWidth = bitmapOptions.outWidth
        var bmHeight = bitmapOptions.outHeight

        //第二次采样：计算采样率
        while (bmWidth > maxWidth || bmHeight > maxHeight){
            //每次压缩50%
            sampleSize *= 2
            //重新图片大小
            bmWidth /= sampleSize
            bmHeight /= sampleSize
        }

        //加载图片
        bitmapOptions.inJustDecodeBounds= false //关闭解析图片边界大小
        bitmapOptions.inSampleSize = sampleSize
        bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565 //编码格式

        return BitmapFactory.decodeResource(resources, resId, bitmapOptions)
    }

    /**
     * 方法三：矩阵压缩
     */
    fun compressMatrixBitmap(resources: Resources, resId: Int, sx: Float, sy: Float): Bitmap{
        var matrix = Matrix()
        matrix.setScale(sx, sy)
        var bm = BitmapFactory.decodeResource(resources, resId)
        return Bitmap.createBitmap(bm, 0,0, bm.width, bm.height, matrix, true)
    }

    /**
     * 方法四：RGB_565压缩
     */
    fun compressRGB565Bitmap(resources: Resources, resId: Int): Bitmap{
        var options = BitmapFactory.Options()
        options.inPreferredConfig = Bitmap.Config.RGB_565
        return BitmapFactory.decodeResource(resources, resId, options)
    }

    /**
     * 方式五：Scale压缩
     */
    fun compressScaleBitmap(resources: Resources, resId: Int, dstWidth: Int, dstHeight: Int): Bitmap{
        var bm = BitmapFactory.decodeResource(resources, resId)
        return Bitmap.createScaledBitmap(bm, dstWidth, dstHeight, true)
    }
}